<template>
  <div class="carousel-box" ref="carouselBox" @mouseover="aniTimerPause" @mouseleave="aniTimerPlay">
    <ul
      class="ul-img"
      :style="'transform:translateX('+ulX+'px);transition: '+curDuration+'s;width:'+ulImgWidth+'px'"
    >
      <li v-for="item in list" :key="item.imgUrl" :style="'width:'+boxWidth+'px'">
        <img :src="item.imgUrl" alt />
      </li>
    </ul>
    <ul class="ul-list">
      <span :style="'transform: translateX('+activeX+'px);'"></span>
      <li v-for="i in listSize" :key="i"></li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "carousel",
  data() {
    return {
      ulX: 0,
      count: 0,
      ulListX: 15,
      activeX: 15,
      aniTimer: null,
      boxWidth: 0,
      ulImgWidth: 0,
      curDuration: 0,
      listSize: 0,
      status: 'play'
    };
  },
  props: {
    list: {
      type: Array,
      default: []
    },
    duration: {
      type: Number,
      default: 2
    }
  },
  mounted() {
    this.listSize = this.list.length;
    this.list.push(this.list[0]);
    this.boxWidth = this.$refs.carouselBox.offsetWidth || 1200;
    this.ulImgWidth = this.boxWidth * this.list.length;
    this.initAniTimer();
  },
  methods: {
    aniTimerPause() {
      clearInterval(this.aniTimer);
    },
    aniTimerPlay() {
      this.initAniTimer();
    },
    initAniTimer() {
      if (this.status === "pause") return; 
      let d1 = this.duration * 1000 * 1.5;
      let d2 = this.duration * 1000 * 2.5;
      this.aniTimer = setInterval(() => {
        this.count++;
        this.ulX = -this.boxWidth * this.count;
        this.activeX += 35;
        this.curDuration = 3;
        if (this.count == this.list.length - 1) {
          this.count = 0;
          this.activeX = 15;
          setTimeout(() => {
            this.curDuration = 0;
            this.ulX = 0;
          }, this.duration * 1000 * 1.5);
        }
      }, this.duration * 1000 * 2.5);
    }
  }
};
</script>

<style lang="less" scoped>
div.carousel-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  cursor: pointer;

  ul.ul-img {
    width: 4800px;
    height: 100%;
    position: relative;

    li {
      height: 100%;
      float: left;
      width: 1200px;
    }

    img {
      width: 100%;
      height: 100%;
    }
  }

  ul.ul-list {
    position: absolute;
    bottom: 0;
    display: flex;
    flex-direction: row;
    width: 100%;
    justify-content: center;

    li {
      width: 15px;
      height: 15px;
      border-radius: 50%;
      background-color: #7f8c8d;
      margin-right: 20px;
      margin-bottom: 5px;
    }

    span {
      width: 15px;
      height: 15px;
      border-radius: 50%;
      background-color: #1abc9c;
    }
  }

  li {
    list-style: none;
  }
}
</style>